<?php


namespace app\zhongcan\controller;


use app\zhongcan\model\NavModel;
use app\zhongcan\validate\NavValidate;
use cmf\controller\AdminBaseController;
use think\Request;

class NavController extends AdminBaseController
{
    //导航菜单表首页
    public function index()
    {
        $title = input('title');
        $where = [];
        if (!empty($title)){
            $where[] = ['title','like',"%$title%"];
        }
        $data = NavModel::order(['list_order'=>'desc','id'=>'desc'])
            ->where($where)
            ->paginate(4);
        $data->appends(request()->param());
        $this->assign('nav',$data);
        return $this->fetch();
    }
    //添加页面
    public function add()
    {
        return $this->fetch();
    }
    //添加功能
    public function addPost(Request $request)
    {
        $data = $request->param();
        //验证
        $validate = new NavValidate();
        $res = $validate->scene('add')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $add = NavModel::create($data);
        if($add){
            $this->success('添加成功','Nav/index');

        }else{
            $this->error('添加失败');
        }
    }
    //修改页面
    public function edit()
    {
        $id = input('id');
        $data = NavModel::find($id);
        return $this->fetch('edit',[
            'nav'=>$data
        ]);

    }
    //修改功能
    public function editPost(Request $request)
    {
        $data = $request->param();
        //验证
        $validate = new NavValidate();
        $res = $validate->scene('edit')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $nav = NavModel::find($data['id']);
        if (!$nav){
            $this->error('未查询到数据');
        }
        $nav->title = $data['title'];
        $nav->url = $data['url'];
        $nav->pid = $data['pid'];
        if ($nav->save()){
            $this->success('保存成功','Nav/index');
        }else{
            $this->error('保存失败');
        }

    }
    //删除功能
    public function del()
    {
        $id = input('id');
        $del = NavModel::destroy($id);
        if ($del){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }

    }
    //排序
    public function listOrder()
    {
        $val = parent::listOrders(new NavModel());
        if ($val){
            $this->success('排序成功');
        }else{
            $this->error('排序失败');
        }

    }
}